#!/usr/bin/env python2
# -*- coding: utf-8 -*-


import traceback

from Ump.schedule.jobs.base import JobBase
from Ump.schedule.utils import log_info_run
from Ump.objs.alert.api import AlertApi
from Ump.objs.session_wrapper import _sw
from Ump.common import log
from Ump.objs.db import models


job_log = log.get_logger('Schedule')


alert_api = AlertApi()


class HostSyncJob(JobBase):

    @log_info_run()
    def run(self, context):
        """ump-sync, sync host and host's disks.

        """
        msgs = []
        cluster = models.Cluster.query.first()

        if not cluster.hosts:
            return ''
            
        try:
            self.cluster_manager.cluster_host_sync(cluster.id)
        except Exception, e:
            traceback.print_exc()
            msg = 'Error cluster sync cluster: %s, %s'%(e, cluster)
            msgs.append(msg)
            
        #同步主机的状态，和资源使用情况
        for host in cluster.hosts:
            try:
                self.hom.host_sync(host.id)
            except Exception, e:
                job_log.warn("sync host %s fail: %s " % (host.ip, e))

        #检查ec和host数量的情况
        if not self.is_fusionnas:
            self._check_ec()

    def _check_ec(self):
        live_hosts = _sw.db_hosts(spec={'lichd_status':'running'})
        host_num = len(live_hosts)
        pools = _sw.db_pools()
        error_dic = {'returncode': 9013, 'level': 'ERROR'}
        warning_dic = {'returncode': 9012, 'level': 'WARNING'}

        error_list = []
        warning_list = []

        for pool in pools:
            if not pool.ec_data :
                continue

            ec_data = int(pool.ec_data)
            ec_code = int(pool.ec_code)
            ec_num = ec_data + ec_code
            if (ec_num + ec_data) < int(host_num):
                error_list += [pool.name]

            if (ec_num + ec_data) == host_num:
                warning_list += [pool.name]

        if error_list:
            error_detail = ','.join(error_list)
            error_dic['detail'] = "The erasure codes number in pool <%s> is larger than current running host number!" \
                                  % error_detail

        if warning_list:
            warning_detail = ','.join(warning_list)
            warning_dic['detail'] = "The erasure codes number in pool <%s> is equal to current running host number!" \
                                    % warning_detail

        wa_list = [warning_dic, error_dic]
        for alert_value in wa_list:
            if alert_value.get('detail'): 
                alert_api.alert_create(alert_value, False, True)


class NodeSyncJob(JobBase):

    @log_info_run()
    def run(self, context):
        self.hom.node_sync()


if __name__ == '__main__':
    HostSyncJob().run(1)

